package android.storefront.common.utils.database;

import java.util.Map;
import java.util.Properties;

import android.storefront.common.utils.properties.PropertiesUtil;

import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

public class InitailDatabase {
	
	private static  InitailDatabase initailDatabase = new InitailDatabase();
	public static InitailDatabase getInstance(){
		return initailDatabase;
	}
	
	private SQLiteDatabase sqLiteDatabase = null;
	private Properties properties = null;
	
	public void initDB(Context context){
		initProperties();
		String name = PropertiesUtil.getInstance().getValue("databaseName");
		//Returns the absolute path on the filesystem where a database created 
		//with openOrCreateDatabase is stored.
		if(!context.getDatabasePath(name).exists()){
			sqLiteDatabase = new DatabaseHelper(context, name).getWritableDatabase();
			try {
				sqLiteDatabase.beginTransaction();
				for(Map.Entry<Object, Object> me : properties.entrySet()){
					if(me.getKey().toString().endsWith("_create")){
						sqLiteDatabase.execSQL(me.getValue().toString());
					}
				}
				sqLiteDatabase.setTransactionSuccessful();
			} catch (SQLException e) {
				e.printStackTrace();
			}finally{
				sqLiteDatabase.endTransaction();
				sqLiteDatabase.close();
			}
			
			//初始化数据库表数据
			initTable(context);
		}
		
	}
	
	private void initTable(Context context){
		InitailDatabaseData initailDatabaseData = InitailDatabaseData.getInstance();
		initailDatabaseData.initialTable("speaker_look_listen.data", context);
		initailDatabaseData.initialTable("questions.data", context);
	}
	
	private void initProperties(){
		properties = SqlitePropertiesUtil.getInstance();
	}

}
